#include <vector>
#include <iostream>
#include <SDL/SDL.h>
#include <GL/glew.h>

#include "Game.h"
#include "util/Timer.h"
#include "exceptions.h"
#include "gui/sdl/SDLGUIEventHandler.h"

using namespace std;

Game::Game() {
	window = NULL;
	resources = NULL;
	gui = NULL;

	resources = new ResourceCollection();

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
		throw GameException(SDL_GetError());

	// Use double buffering
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	window = new GameWindow();

	if (glewInit() != GLEW_OK) {
		throw GameException((const char*)glewGetErrorString(GLEW_VERSION));
	}

	if (!GLEW_VERSION_2_0) {
		throw GameException("OpenGL 2.0 not supported.");
	}

	ticksPerSecond = 1000;
	runLevel = RUNNING;

	SDL_EnableUNICODE(1);
}

void Game::run() {
	float dts;
	long lastTick = 0, currentTick = 0;
	lastTick = Timer::getCurrentTick();

	while (runLevel != EXIT) {
		currentTick = Timer::getCurrentTick();
		dts = ((float)(currentTick - lastTick)) / ticksPerSecond;

		for (unsigned int i = 0; i < eventDispatchers.size(); i++) {
			eventDispatchers[i]->dispatchEvents(dts);
		}

		world->step(dts);
		world->draw();
		gui->draw();
		SDL_GL_SwapBuffers();
		lastTick = currentTick;
	}
}

Game::~Game() {
	if (world != NULL) {
		delete world;
	}
	if (window != NULL) {
		delete window;
	}
	if (resources != NULL) {
		delete resources;
	}
	if (gui != NULL) {
		delete gui;
	}
	SDL_Quit();
}
